/**
 * 
 */
package client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author Fleischhacker
 *
 */
public class ClientUDPThread extends Thread {
	
	private boolean alive;
	private int pUDP;
	private InetAddress address;
	private DatagramSocket dsock = null;
	private Client parent;

	public ClientUDPThread(InetAddress _address, int _pUDP, Client _parent){
		this.address = _address;
		this.pUDP = _pUDP;
		this.parent = _parent;
		alive = false;
	}

	public void run(){
		alive = true;
		try {
			dsock = new DatagramSocket(pUDP);
			while (alive) {
				byte[] buffer = new byte[256];
				DatagramPacket dpacket = new DatagramPacket(buffer, buffer.length);
				dsock.receive(dpacket); //Trying to recieve the UDP Packet from the Server, locks the thread until a response was found
				String recieved = new String(dpacket.getData(), 0, dpacket.getLength());
				System.out.println(translate(recieved));
			}
		}catch(SocketException e){
			//used to end transmisson, goto finally!
		}catch (IOException e) {
			System.out.println("ClientThread Terminated!:"+e.getMessage());
		} finally{
			alive = false;
			if(dsock != null)
				dsock.close();
		}
	}
	
	/**
	 * 
	 * @return
	 */
	private String translate(String _msg){
		if(_msg.startsWith("!new-bid")){ //1 Parameter
			return "You have been overbid on '"+_msg.split(" ")[1]+"'.";
		}
		else if(_msg.startsWith("!auction-ended")){ //3+ Parameter: [1]: username, [2] ammount, [3+] descr
			String subj = "";
			for(int i = 3; i < _msg.split(" ").length; i++)
				subj += _msg.split(" ")[i]+" ";
			if(_msg.split(" ")[1].equalsIgnoreCase(parent.getClientUser()))
				return "The auction '"+subj+"' has ended. You won with '"+_msg.split(" ")[2]+"'.";
			return "The auction '"+subj+"' has ended. "+_msg.split(" ")[1]+" won with '"+_msg.split(" ")[2]+"'.";
		}
		return "";
	}
	
	/**
	 * Shutdown UDP
	 */
	public void shutdown(){
		alive = false;
		if(dsock != null)
			dsock.close(); //Throws SocketException
	}
}
